/***********************************************
 This file is part of redia-bapps-main-ios.
 
 Copyright (c) 2015 Redia A/S
 
 Redia-bapps-main-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-bapps-main-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-bapps-main-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

//
//  BAUserSearchViewController_iPad.m
//  redia-bapps-ios
//
//  Created by Nikolaj Tørring on 10/17/13.
//  Copyright (c) 2013 redia. All rights reserved.
//

#import "BAUserSearchViewController_iPad.h"
#import "BAFlyoutMenuViewController.h"
#import "BALibrarySettings.h"
#import "BASearchResultsColumnViewController.h"
#import "BASlideInViewController.h"
#import "BAPopularItemsViewController.h"
#import "BASearchBar.h"
#import "BAFacet.h"
#import "BATerm.h"
#import "BAPatronSettings.h"

#ifdef BA_IMF_BUILD
#import "IMFPackage.h"
#import "IMFSuggestedPackageTableViewController.h"
#else
@class IMFSuggestedPackageTableViewController;
#endif

@interface BAUserSearchViewController_iPad () {
    NSMutableArray* filterDescriptionsBarButtons;
    NSMutableArray* filterDescriptionStrings;
    BOOL doShowIMFColumn;

}

@property (weak, nonatomic) IBOutlet UIView *popularColumnContainer1;
@property (weak, nonatomic) IBOutlet UIView *popularColumnContainer2;
@property (weak, nonatomic) IBOutlet UIView *popularColumnContainer3;

@property (strong, nonatomic) BAPopularItemsViewController* popularItemsViewController1;
@property (strong, nonatomic) BAPopularItemsViewController* popularItemsViewController2;
@property (strong, nonatomic) BAPopularItemsViewController* popularItemsViewController3;

//@property (weak, nonatomic) IBOutlet UITextField *searchTextFeild;
@property (weak, nonatomic) IBOutlet BASearchBar *mySearchBar;
@property (weak, nonatomic) IBOutlet UIView *topBarView;
@property (weak, nonatomic) IBOutlet UIView *mainView;
@property (weak, nonatomic) IBOutlet UIScrollView *mainScroller;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *searchActivityIndicator;
@property (weak, nonatomic) IBOutlet UIView *filterDescriptionsBar;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *filterDescriptionsBarHeightConstraint;
@property (weak, nonatomic) IBOutlet UILabel *noResultsLabel;

//filter bar
//@property (weak, nonatomic) IBOutlet NSLayoutConstraint *filterDescriptionsContentWidth;
@property (weak, nonatomic) IBOutlet UIScrollView *filterDescriptionsScroller;
//@property (weak, nonatomic) IBOutlet UIImageView *filterDescriptionsSelectionIndicatorImage;
//@property (strong, nonatomic) IBOutlet UIView *filterDescriptionsContent;
@property (strong,nonatomic) UIImageView *filterDescriptionsSelectionIndicatorImageNew;

@property(nonatomic, strong) NSString* currentQuery;


@property (nonatomic, strong) IMFSuggestedPackageTableViewController* mainIMFPackageListViewController;
@property (nonatomic, strong) BASearchResultsColumnViewController* mainUserSearchViewController;
@property (nonatomic, strong) NSMutableArray* filteredUserSearchViewControllers;

@end

@implementation BAUserSearchViewController_iPad

-(void)commonInitBAUserSearchViewController_iPad
{
    filterDescriptionsBarButtons = [NSMutableArray new];
    filterDescriptionStrings = [NSMutableArray new];
}

- (id)init
{
    self = [super init];
    if (self) {
        [self commonInitBAUserSearchViewController_iPad];
    }
    return self;
}

-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        // Custom initialization
        [self commonInitBAUserSearchViewController_iPad];
    }
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self commonInitBAUserSearchViewController_iPad];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    RD_SET_EDGES_FOR_EXTENDED_LAYOUT_IOS7
    BA_FLYOUT_MENU_ADD_BUTTON(BASpecialNavigationBarConfigurationDefault)
    [self.view setBackgroundColor:[[BALibrarySettings instance] getCustomerColorNormal]];
    
    self.mainScroller.delegate = self;
    
    BA_LABEL_SET_FONT_REGULAR(self.noResultsLabel);
    
    //self.filterDescriptionsBarHeightConstraint.constant = 8;
    
    self.popularItemsViewController1 = [BAPopularItemsViewController new];
    [self.popularColumnContainer1 addSubview:self.popularItemsViewController1.view];
    [self addChildViewController:self.popularItemsViewController1];
    [BAUtils setViewToFillParent:self.popularItemsViewController1.view];
    
    self.popularItemsViewController2 = [BAPopularItemsViewController new];
    [self.popularColumnContainer2 addSubview:self.popularItemsViewController2.view];
    [self addChildViewController:self.popularItemsViewController2];
    [BAUtils setViewToFillParent:self.popularItemsViewController2.view];
    
    self.popularItemsViewController3 = [BAPopularItemsViewController new];
    [self.popularColumnContainer3 addSubview:self.popularItemsViewController3.view];
    [self addChildViewController:self.popularItemsViewController3];
    [BAUtils setViewToFillParent:self.popularItemsViewController3.view];
    
    /*
    self.filterDescriptionsContent.translatesAutoresizingMaskIntoConstraints=NO;
    
    [self.filterDescriptionsScroller addSubview:self.filterDescriptionsContent];
    NSDictionary* viewsdict = NSDictionaryOfVariableBindings(_filterDescriptionsContent);
    [self.filterDescriptionsScroller addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_filterDescriptionsContent]|" options:0 metrics:0 views:viewsdict]];
    [self.filterDescriptionsScroller addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_filterDescriptionsContent(50)]|" options:0 metrics:0 views:viewsdict]];
*/
    
    self.filterDescriptionsSelectionIndicatorImageNew = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"facets-indicator-ipad"]]; //17x9
    [self.mainScroller addSubview:self.filterDescriptionsSelectionIndicatorImageNew];
    [self resetIndicatorFrame];
    self.filterDescriptionsSelectionIndicatorImageNew.hidden=YES;
    
    if (self.currentQuery != nil) {
        [self.mySearchBar setText:self.currentQuery];
        [self search:self.currentQuery];
        [self setPopularHidden:YES];
    }
    else{
        [self setPopularHidden:NO];
        [self loadPopular];
    }
    
    if ([[BAPatronSettings instance] isUserAllowedIMFEditorAccessForCurrentLibrary]) {
        [self.mySearchBar setPlaceholder:@"Søg i materialer"];
    }
}

-(void)dealloc
{
    [BARPCManager closeConnectionsForView:self];
    [self removeAllSearchViewControllers];
    
}

-(void)resetIndicatorFrame
{
    self.filterDescriptionsSelectionIndicatorImageNew.frame = CGRectMake(12, 0, 17, 9);
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self enableUserInteraction];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)loadPopular{
    [BARPCManager getPopularAsyncFromView:self
                                listCount:3
                                 listSize:10
                              resultBlock:^(NSArray *result) {
                                  if (result.count > 0) {
                                      BAPopular* popular = [result objectAtIndex:0];
                                      [self.popularItemsViewController1 setPopular:popular];
                                  }else{
                                      [self.popularItemsViewController1 setPopular:nil];
                                  }
                                  
                                  if (result.count > 1) {
                                      BAPopular* popular = [result objectAtIndex:1];
                                      [self.popularItemsViewController2 setPopular:popular];
                                  }else{
                                      [self.popularItemsViewController2 setPopular:nil];
                                  }
                                  
                                  if (result.count > 2) {
                                      BAPopular* popular = [result objectAtIndex:2];
                                      [self.popularItemsViewController3 setPopular:popular];
                                  }else{
                                      [self.popularItemsViewController3 setPopular:nil];
                                  }
                              }
                               errorBlock:^(int code, NSString *error) {
                                   DLog(@"search error: %@",error);
                                   //                               [self showSearchError];
                               }
     ];
}

-(void)search:(NSString*)query{
    _currentQuery = query;
    if (self.isViewLoaded) {
        [self.mySearchBar setText:query];
        
        [self removeAllSearchViewControllers];
        [BARPCManager closeConnectionsForView:self];
        
        [self setPopularHidden:YES];
        [self.searchActivityIndicator startAnimating];
        [self clearFilterDescriptionBarButtons];
        
//        CGRect newframe = CGRectMake(0, 0, 342, self.mainScroller.bounds.size.height);

#ifdef BA_IMF_BUILD
        if ([[BALibrarySettings instance] isImfEnabled]) {
            self.mainIMFPackageListViewController = [IMFSuggestedPackageTableViewController new];
            [self.mainScroller addSubview:self.mainIMFPackageListViewController.view];
//            self.mainIMFPackageListViewController.view.frame = newframe;
            [self addChildViewController:self.mainIMFPackageListViewController];
            self.mainIMFPackageListViewController.view.hidden=YES;
//            newframe.origin.x += 342;
        }
#endif
        
        self.mainUserSearchViewController = [[BASearchResultsColumnViewController alloc] initWithNibName:@"BASearchResultsColumnViewController" bundle:nil];
        [self.mainUserSearchViewController setSearchQuery:query];
        [self.mainUserSearchViewController loadResults];
        self.noResultsLabel.hidden=YES;
        
        [self.mainScroller addSubview:self.mainUserSearchViewController.view];
        self.mainUserSearchViewController.view.hidden = YES;
        
        [self addChildViewController:self.mainUserSearchViewController];
        
//        [self.mainUserSearchViewController.view setFrame:newframe];
        self.mainUserSearchViewController.searchResultDelegate = self;
//        self.mainScroller.contentSize = CGSizeMake(newframe.origin.x+newframe.size.width, newframe.size.height);
        
        self.filterDescriptionsSelectionIndicatorImageNew.hidden=YES;
    }
}

-(void)searchResultsColumnViewController:(BASearchResultsColumnViewController *)searchResultsColumnViewController updatedWithSearchResult:(BASearchResult *)result
{
    [self.searchActivityIndicator stopAnimating];
    if (result!=nil) {
        if (result.count>0) {
#ifdef BA_IMF_BUILD
            doShowIMFColumn = [[BALibrarySettings instance] isImfEnabled] && [result.imf count]>0;
#else
            doShowIMFColumn = NO;
#endif
            
            self.mainUserSearchViewController.view.hidden = NO;
            
            if (doShowIMFColumn) {
#ifdef BA_IMF_BUILD
                [self.mainIMFPackageListViewController setHiglightedTitleColor:YES];
#endif
            }
            else{
                [self.mainUserSearchViewController setHiglightedTitleColor:YES];
            }
            
            
            self.mainUserSearchViewController.view.alpha = 0;
            [UIView animateWithDuration:0.25
                             animations:^{
                                 self.mainUserSearchViewController.view.alpha = 1;
                             }];
            
            CGFloat viewWidth = 342;
            
            
           
#ifdef BA_IMF_BUILD
            if (doShowIMFColumn) {
                self.mainIMFPackageListViewController.packages = result.imf;
                self.mainIMFPackageListViewController.view.hidden=NO;
            } else {
                if (self.mainIMFPackageListViewController!=nil) {
                    self.mainIMFPackageListViewController.view.hidden=YES;
                }
            }
#endif
            
            
//            CGFloat currentX = doShowIMFColumn ? 342*2 : 342;
            CGFloat currentX = 0;

#ifdef BA_IMF_BUILD
            if (doShowIMFColumn) {
                [self.mainIMFPackageListViewController.view setFrame:CGRectMake(currentX, 0, viewWidth, self.mainScroller.bounds.size.height)];
                currentX += viewWidth;
            }
#endif
            [self.mainUserSearchViewController.view setFrame:CGRectMake(currentX, 0, viewWidth, self.mainScroller.bounds.size.height)];
            currentX += viewWidth;
            
            self.filteredUserSearchViewControllers = [NSMutableArray new];
            
            int index = 0;
            
            if ([result.facets count]>0) {
                BAFacet* facet1 = [result.facets objectAtIndex:0];
                
                //create view controllers
                for (BATerm* facetTerm in facet1.terms) {
                    CGRect newframe = CGRectMake(currentX, 0, viewWidth, self.mainScroller.bounds.size.height);
                    
                    BASearchResultsColumnViewController* newcolumn = [[BASearchResultsColumnViewController alloc] initWithNibName:@"BASearchResultsColumnViewController" bundle:nil];
                    [self.mainScroller addSubview:newcolumn.view];
                    newcolumn.view.frame = newframe;
                    [self addChildViewController:newcolumn];
                    
                    [self.filteredUserSearchViewControllers addObject:newcolumn];
                    [newcolumn setSearchQuery:self.currentQuery];
                    [newcolumn setSearchQueryFilter:@{
                                                      [[BALibrarySettings instance] getDefaultMaterialTypeFilter]: @[facetTerm.term]
                                                      }];
                    if (currentX<self.mainScroller.bounds.size.width) {
                        [newcolumn loadResults];
                    }
                    
                    newcolumn.view.alpha=0;
                    [UIView animateWithDuration:0.25
                                          delay:0.05*index
                                        options:0
                                     animations:^{
                                         newcolumn.view.alpha=1;
                                     }
                                     completion:nil];
                    
                    currentX += viewWidth;
                    index++;
                }
                self.mainScroller.contentSize = CGSizeMake(currentX, self.mainScroller.bounds.size.height);
                
                //create filter buttons
                filterDescriptionsBarButtons = [NSMutableArray new];
                filterDescriptionStrings = [NSMutableArray new];
                
                int cur_x = 15;
                
                if (doShowIMFColumn) {
//                    cur_x += 342;
                    cur_x += [self createNewFilterDescriptionButtonWithTerm:@"INSPIRATION" count:result.count isSelected:NO atX:cur_x];
                    [filterDescriptionStrings addObject:@""];
                    cur_x += 40;
                }
                
                cur_x += [self createNewFilterDescriptionButtonWithTerm:@"ALLE" count:result.count isSelected:NO atX:cur_x];
                [filterDescriptionStrings addObject:@""];
                cur_x += 40;
                
                
                for (BATerm* term in facet1.terms) {
                    CGFloat buttonWidth = [self createNewFilterDescriptionButtonWithTerm:term.term count:term.frequence isSelected:NO atX:cur_x];
                    [filterDescriptionStrings addObject:term.term];
                    cur_x += buttonWidth + 40;
                }
                
                [self resetIndicatorFrame];
                self.filterDescriptionsSelectionIndicatorImageNew.hidden=NO;
                [self.mainScroller bringSubviewToFront:self.filterDescriptionsSelectionIndicatorImageNew];

                [self.filterDescriptionsScroller setContentSize:CGSizeMake(cur_x, 39)];
                [self selectFilterButton:[filterDescriptionsBarButtons objectAtIndex:0]];
                

                if (doShowIMFColumn) {
#ifdef BA_IMF_BUILD
                    self.filterDescriptionsSelectionIndicatorImageNew.frame = [self calculateIndicatorFrameForSearchResultController:self.mainIMFPackageListViewController];
#endif
                }
                else{
                    self.filterDescriptionsSelectionIndicatorImageNew.frame = [self calculateIndicatorFrameForSearchResultController:self.mainUserSearchViewController];
                }
                
            }
            
        } else {
            self.noResultsLabel.hidden=NO;
        }
    } else {
        //FIXME: handle search error
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Problemer med netværket"
                                                        message:@"Søgningen kunne ikke gennemføres på grund af problemer med netværket. Prøv venligst igen senere."
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
    }
}

-(void)clearFilterDescriptionBarButtons
{
    for (UIButton* b in filterDescriptionsBarButtons) {
        [b removeFromSuperview];
    }
    [filterDescriptionsBarButtons removeAllObjects];
    [self.filterDescriptionsScroller setContentOffset:CGPointZero animated:NO];
}


-(CGFloat)createNewFilterDescriptionButtonWithTerm:(NSString*)term count:(int)count isSelected:(BOOL)isSelected atX:(CGFloat)cur_x
{
    UIButton* newbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    if (isSelected) {
        [newbutton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [newbutton setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    } else {
        [newbutton setTitleColor:[[UIColor whiteColor] colorWithAlphaComponent:0.40] forState:UIControlStateNormal];
        [newbutton setTitleColor:[[UIColor grayColor] colorWithAlphaComponent:0.40] forState:UIControlStateHighlighted];
    }
    NSString* titletext = [term uppercaseString]; //[[NSString stringWithFormat:@"%@ (%d)",term, count] uppercaseString];
    [newbutton setTitle:titletext forState:UIControlStateNormal];
    if (isSelected ) {
        [newbutton.titleLabel setFont:BA_FONT_REGULAR(13)];
    } else {
        [newbutton.titleLabel setFont:BA_FONT_LIGHT(13)];
    }
    
    CGSize textrect = [titletext sizeWithFont:newbutton.titleLabel.font];
    CGFloat buttonWidth = textrect.width + 10;
    newbutton.frame = CGRectMake(cur_x, 6, buttonWidth, 30);
    //was:[self.filterDescriptionsContent addSubview:newbutton];
    [self.filterDescriptionsScroller addSubview:newbutton];
    
    [newbutton addTarget:self action:@selector(filterButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    [filterDescriptionsBarButtons addObject:newbutton];
    
    return buttonWidth;
}

-(void)selectFilterButton:(UIButton*)sel_button
{
    [sel_button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sel_button setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [sel_button.titleLabel setFont:BA_FONT_REGULAR(13)];
    
    CGRect sel_rect = sel_button.frame;
    CGFloat superviewWidth = sel_button.superview.bounds.size.width;
    CGFloat extraWidth = superviewWidth - sel_rect.size.width;
    sel_rect.origin.x -= extraWidth;
    sel_rect.size.width += 2*extraWidth;
    
    //[self.filterDescriptionsScroller scrollRectToVisible:sel_rect animated:YES];
    
    
    for (UIButton* otherbutton in filterDescriptionsBarButtons) {
        if (otherbutton!=sel_button) {
            [otherbutton setTitleColor:[[UIColor whiteColor] colorWithAlphaComponent:0.60] forState:UIControlStateNormal];
            [otherbutton setTitleColor:[[UIColor grayColor] colorWithAlphaComponent:0.60] forState:UIControlStateHighlighted];
            [otherbutton.titleLabel setFont:BA_FONT_LIGHT(13)];
            
        }
    }
    
}

-(IBAction)filterButtonClicked:(id)sender
{
    NSUInteger button_index = [filterDescriptionsBarButtons indexOfObject:sender];

    if (button_index!=NSNotFound && button_index<[filterDescriptionStrings count] && button_index<[filterDescriptionsBarButtons count]) {
        NSString* filtertext = [filterDescriptionStrings objectAtIndex:button_index];
        [self selectFilterButton:[filterDescriptionsBarButtons objectAtIndex:button_index]];
        
        BAColumnViewController* selectedVC = nil;
        
#ifdef BA_IMF_BUILD
        if (doShowIMFColumn && button_index==0) {
            [self.mainUserSearchViewController setHiglightedTitleColor:NO];
            selectedVC=self.mainIMFPackageListViewController;
            [self.mainIMFPackageListViewController setHiglightedTitleColor:YES];
            for (BASearchResultsColumnViewController* filteredVC in self.filteredUserSearchViewControllers) {
                [filteredVC setHiglightedTitleColor:NO];
            }
        } else if ((doShowIMFColumn && button_index==1) || button_index==0) {
            [self.mainIMFPackageListViewController setHiglightedTitleColor:NO];
            selectedVC=self.mainUserSearchViewController;
            [self.mainUserSearchViewController setHiglightedTitleColor:YES];
            for (BASearchResultsColumnViewController* filteredVC in self.filteredUserSearchViewControllers) {
                [filteredVC setHiglightedTitleColor:NO];
            }
        } else
#endif
        {
            [self.mainUserSearchViewController setHiglightedTitleColor:NO];
            for (BASearchResultsColumnViewController* filteredVC in self.filteredUserSearchViewControllers) {
                [filteredVC setHiglightedTitleColor:NO];
                NSDictionary* filterdict = filteredVC.searchQueryFilter;
                NSArray* typefilters = [filterdict objectForKey:[BALibrarySettings instance].getDefaultMaterialTypeFilter];
                if ([typefilters count]>0) {
                    NSString* typefilterstring = [typefilters objectAtIndex:0];
                    if (typefilterstring!=nil && [typefilterstring compare:filtertext options:NSCaseInsensitiveSearch]==NSOrderedSame) {
                        selectedVC=filteredVC;
                        [filteredVC setHiglightedTitleColor:YES];
                    }
                }
            }
        }
        
        if (selectedVC!=nil) {
            CGRect showframe = selectedVC.view.frame;
            showframe.origin.x -= showframe.size.width;
            showframe.size.width += 2*showframe.size.width;
            
            [self.mainScroller scrollRectToVisible:showframe animated:YES];
            CGRect indicatorFrame = [self calculateIndicatorFrameForSearchResultController:selectedVC];
            
            [UIView animateWithDuration:0.75
                             animations:^{
                                 self.filterDescriptionsSelectionIndicatorImageNew.frame = indicatorFrame;
                             }];
        }
    }
    
}

-(CGRect)calculateIndicatorFrameForSearchResultController:(BAColumnViewController*)selectedVC
{
    CGRect selectedVCTitleFrame = [selectedVC getTitleLabelRectConvertedToView:self.mainScroller];
    
    CGRect indicatorFrame = self.filterDescriptionsSelectionIndicatorImageNew.frame;
    indicatorFrame.origin.x = selectedVCTitleFrame.origin.x + (selectedVCTitleFrame.size.width/2.0) - 8;
    return indicatorFrame;
}

-(void)setPopularHidden:(BOOL)hide{
    //reverse hide others
    self.mainScroller.hidden=!hide;
    self.filterDescriptionsBar.hidden=!hide;
    self.noResultsLabel.hidden=YES; //always hide this when state changes
    
    [self.popularItemsViewController1.view setHidden:hide];
    [self.popularItemsViewController2.view setHidden:hide];
    [self.popularItemsViewController3.view setHidden:hide];
    
}

#pragma mark - UIScrollViewDelegate

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    for (BASearchResultsColumnViewController* columnVC in self.filteredUserSearchViewControllers) {
        if (!columnVC.loadResultsStarted) {
            
            CGRect colframe = columnVC.view.frame;
            CGFloat offsetXMin = self.mainScroller.contentOffset.x;
            CGFloat offsetXMax = offsetXMin + self.mainScroller.bounds.size.width;
            
            
            if (colframe.origin.x < offsetXMax && offsetXMin < colframe.origin.x+colframe.size.width) {
                [columnVC loadResults];
            }
        }
    }
}

#pragma mark - Flyout menu

BA_FLYOUT_MENU_ADD_CALLBACK

- (void)enableUserInteraction
{
    self.view.userInteractionEnabled = YES;
    self.tabBarController.tabBar.userInteractionEnabled = YES;
}

- (void)disableUserInteraction
{
    self.view.userInteractionEnabled = NO;
    self.tabBarController.tabBar.userInteractionEnabled = NO;
}

#pragma mark - UISearchBarDelegate

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    if (searchBar.text.length > 0) {
        [BARPCManager closeConnectionsForView:self];
        _currentQuery = searchBar.text;
        [searchBar resignFirstResponder];
        [self removeAllSearchViewControllers];
        [self search:self.currentQuery];
        [self setPopularHidden:YES];
    }
}

-(void)removeAllSearchViewControllers
{
    self.mainUserSearchViewController.searchResultDelegate = nil;
    [self.mainUserSearchViewController cancelAllRPCConnections];
    
    [self.mainUserSearchViewController.view removeFromSuperview];
    [self.mainUserSearchViewController removeFromParentViewController];
    self.mainUserSearchViewController = nil;
    
#ifdef BA_IMF_BUILD
    if (self.mainIMFPackageListViewController!=nil) {
        [self.mainIMFPackageListViewController.view removeFromSuperview];
        [self.mainIMFPackageListViewController removeFromParentViewController];
        self.mainIMFPackageListViewController = nil;
    }
#endif
    
    for (BASearchResultsColumnViewController* subvc in self.filteredUserSearchViewControllers) {
        [subvc cancelAllRPCConnections];
        [subvc.view removeFromSuperview];
        [subvc removeFromParentViewController];
    }
    self.filteredUserSearchViewControllers = nil;
}

//FIXME: not implemented catching when search bar clear button clicked
/* should be something like
-(BOOL)textFieldShouldClear:(UITextField *)textField{
    _currentQuery = nil;
    [self.searchResultsColumnViewController1 setSearchQuery:nil];
    [self.searchResultsColumnViewController2 setSearchQuery:nil];
    [self.searchResultsColumnViewController3 setSearchQuery:nil];
    [self setPopularHidden:NO]; //FIXME: load populars if not already loaded
    return YES;
}
*/

@end
